<template>
  <div class="pageDdingCustomersPad">
    <!-- 页面内容 -->
    <div class="content">
      <van-form class="contentView" @failed="onFailed" ref="forms" @submit="submit">
        <van-cell-group inset>
          <!-- 姓名-->
          <van-field label="姓名" placeholder="如填写，请填写真实准确姓名" v-model="customName" name="姓名" :maxlength="32" input-align="right" autocomplete="off"
            :rules="zhrules" />
          <!-- 证件类型 -->
          <van-field
           v-model="credType"
           is-link
           readonly
           name="picker"
           label="证件类型"
           autocomplete="off"
           placeholder="点击选择证件类型"
           :disabled="customName?false:true"
           @click="carShowClick"
          />
          <van-popup v-model:show="carshowPicker" position="bottom">
            <van-picker
              :columns="carcolumns"
              @confirm="caronConfirm"
              @cancel="cancel"
            />
          </van-popup>
          <span v-if="credType== '' && credNum!=''" class="crn">您已填写证件号码，请选择证件类型</span>
          <!-- <van-field label="证件类型" model-value="身份证" name="证件类型" readonly input-align="right" /> -->
          <!-- 通过 validator 进行身份证格式校验 -->
          <van-field label="证件号码" v-model="credNum" :disabled="customName?false:true" maxlength=18 name="validator" placeholder="请输入证件号码" autocomplete="off"
            input-align="right" :rules="[{ required: isCaedType, message: '请填写身份证号' }, { validator, message: '证件号码格式错误！' } ]" />
           <span v-if="credType!= '' && credNum==''" class="crn">您已选择证件类型，请填写证件号码</span>
          <!-- 性别 -->
          <van-field name="sex" v-if="false" label="性别" :disabled="customName?false:true"  readonly input-align="right">
            <template #input>
              <van-radio-group :disabled="true" v-model="sex" direction="horizontal">
                <van-radio name="0">男</van-radio>
                <van-radio name="1">女</van-radio>
              </van-radio-group>
            </template>
          </van-field>

          <!-- 出生日期 -->
          <!-- is-link 右边箭头 -->
          <van-field v-model="birthday" v-if="false" :disabled="customName?false:true" readonly name="datePicker" label="出生日期" input-align="right" />
          <!-- @click="showPicker = true" -->
          <!-- <van-popup v-model:show="showPicker" position="bottom">
            <van-date-picker :formatter="formatter" :min-date="minDate" :max-date="maxDate" @confirm="onConfirm"
              @cancel="showPicker = false" />
          </van-popup> -->

          <!-- 报告类型 -->
          <van-field name="reportType" label="报告类型 *" input-align="right">
            <template #input>
              <van-radio-group  v-model="reportType" direction="horizontal" 
                required :rules="[{required:true,message:'请选择报告类型'}]">
                <van-radio name="1">简版
                  <template #icon="props">
                    <img style="width: 13px; height: 13px; margin-top: 3px;" class="img-icon" :src="props.checked ? activeIcon : inactiveIcon" />
                  </template>
                </van-radio>
                <van-radio name="2">详版
                  <template #icon="props">
                    <img style="width: 13px; height: 13px; margin-top: 3px;" class="img-icon" :src="props.checked ? activeIcon : inactiveIcon" />
                  </template>
                </van-radio>
              </van-radio-group>
            </template>
          </van-field>
          
          <van-field v-model="reportParam" is-link readonly name="picker" label="演示期间 *" placeholder="终身" input-align="right"
            @click="reportParamShowPicker = true" />
          <van-popup v-model:show="reportParamShowPicker" position="bottom">
            <van-picker :columns="columns" @confirm="reportParamOnConfirm" @cancel="reportParamShowPicker = false" />
          </van-popup>
          <van-field label="任务备注" v-model="remark"  rows="3" autosize  type="textarea"  :maxlength="80" input-align="right" placeholder="您可以在此处输入备注信息"/>
          <div class='seat'></div>
        </van-cell-group>
        <div>
          <van-button class="primaryButton" block native-type="submit" v-log-button-name="'保单检视_新客邀请_发起邀请'">发起邀请</van-button>
          <!-- <van-button round block type="primary" native-type="submit">
            生成链接
          </van-button> -->
        </div>
      </van-form>

    </div>
  </div>
</template>

<script lang="ts" setup name="pageDdingCustomersPad">
import { useRouter, useRoute } from "vue-router"
import { Toast } from '/@/utils/Message';
import { onMounted } from "vue"
import { reactive, ref } from 'vue'
import { createInspectionTask } from "/@/api/auth/wart"
import activeIcon from "../../assets/img/features/activeIcon.png"
import inactiveIcon from "../../assets/img/features/inactiveIcon.png"

import { sm2 } from 'sm-crypto';
//公钥串---加密使用
const publicKey = ref<string>("044291b381a039a8d7d02d7272d2d7c78a30d33e3eeaa0b509bf77d2376582ab2d573730e6bfe9a53bad53f53ac1a85d9c11050931f04bc8b3afc04144d5a6f9be")
//私钥串---解密使用
const privateKey = ref<string>("5aa03412c3051e1d4cf9d19cfbeeec70c28f388c9f82747cc912096c9cd44bea")
const router = useRouter()
const route = useRoute()
const leftTetx = ref<string>("")
const titleTest = ref<string>("添加客户")
let forms = ref()
// const zhrules = [{ required: true, message: '请输入姓名' }, { pattern: /^.{2,}$/, message: '姓名格式错误', trigger: 'onBlur' }]
//用户姓名
const customName = ref<string>("")
//身份证号码
const credNum = ref<string>("")
const credNumShow = ref<boolean>(true)
//性别
let sex = ref('');
let credType = ref('')
let isCaedType:boolean = credType.value !== '' ? true : false
//报告类型
const reportType = ref("1")
// 防止点击
const show = ref(true)
//出生日期
const birthday = ref('');
//备注
const remark = ref<string>('')
const showPicker = ref(false);
const onConfirm = ({ selectedValues }:any) => {
  birthday.value = selectedValues.join('-');
  showPicker.value = false;
}
const carshowPicker = ref(false);
const carcolumns = [
    { text: '身份证', value: '111' }
];

const caronConfirm = ({ selectedOptions }:any) => {
  credType.value = selectedOptions[0]?.text;
  carshowPicker.value = false;
};
const cancel = () => {
  credType.value = ''
  carshowPicker.value = false
}
//和业务需求核对日期
//1.开始日期
const minDate = ref<any>(new Date(1900, 0, 1))
//2.当前日期
const maxDate = ref<any>(new Date())
const formatter = (type, option) => {
  if (type === 'year') {
    option.text += '年';
  }
  if (type === 'month') {
    option.text += '月';
  }
  if (type === 'day') {
    option.text += '日';
  }
  return option;
};

//参数
const reportParamName = ref<string>("3")
const reportParam = ref<string>("终身")
const reportParamShowPicker = ref(false);
const reportParamOnConfirm = ({ selectedOptions }):void => {
  reportParam.value = selectedOptions[0]?.text;
  reportParamName.value = selectedOptions[0]?.value;
  reportParamShowPicker.value = false;
};

// 后期咨询需求
const columns = [
  { text: '终身', value: '3' },
  { text: '30年', value: '2' },
  { text: '20年', value: '1' },
  { text: '10年', value: '0' },  
];

const goback = ():void => {
    // Toast('返回上一页面')
    router.go(-1)
}
const validatorName =(v:any)=>{
  if(v){
    const testName = /^.{2,}$/
    return testName.test(v)
  }else{
    console.log("清空了姓名")
    //清空姓名后，需要清除证件类型、证件号码’性别、出生日期
    credType.value = ''
    credNum.value = ''
    sex.value = ''
    birthday.value = ''
  }
}
// 姓名校验规则
const zhrules = [
  { required: false, message: '请输入姓名' }, 
  { validator:validatorName, message: '姓名格式错误' } 
]
// 证件类型点击事件
const carShowClick = ()=>{
  if(!!customName.value){
    carshowPicker.value = true
  }else{
    Toast('请先输入姓名')
  }
}
//身份证校验规则
const validator = (v) => {
  if(v){
    const card15 = /^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}[0-9Xx]$/
    const card18 = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
    // 出生日期
    const regexp = /^(\d{6})(\d{4})(\d{2})(\d{2})\d{3}(\w)$/;
    if (card15.test(v) || card18.test(v)) {
      /** idCard  '1'= 男  '2'= 女*/
      // console.log("身份证输入正确！")
      birthday.value = getBirthday(v)
      // console.log(parseInt(v.slice(-2, -1), 10) % 2)
      if (parseInt(v.slice(-2, -1), 10) % 2 == 1) {
        sex.value = '0'
        // console.log("身份证 男")
      } else {
        sex.value  = '1'
        // console.log("身份证 女")
      }
    } else {
      sex.value  = '2'
    }
    credNumShow.value = card15.test(v) || card18.test(v)
    return card15.test(v) || card18.test(v)
  } else {
      credNumShow.value = true
  }
}
const getBirthday = (idCard) => {
    let birthday = '';
    if (idCard.length === 15) {
      birthday = '19' + idCard.substring(6, 12);
    } else if (idCard.length === 18) {
      birthday = idCard.substring(6, 14);
    }
    return birthday.replace(/(.{4})(.{2})(.{2})/, '$1-$2-$3')
}

const onFailed = (errorInfo):void => {
  console.log('failed', errorInfo);
};
// 加密方法
const JIAMIPublicData=(data)=> {
    const cipherMode = 1;
    const result = sm2.doEncrypt(data, publicKey.value,cipherMode);
    return `04${result}`;
}
// 解密方法
const JIMIPublicData=(data)=> {
    const cipherMode = 1;
    //data为加密的数据
    const result = sm2.doDecrypt(data, privateKey.value,cipherMode).split('04')[1]
    return result;
}
// 邀请客户submit
const submit = ():void => {
  if(show.value){
    if(!credNumShow.value){
      Toast('身份证格式错误')
      return
    }
    show.value = false
    // console.log(customName,credNum,sex,reportType,birthday,reportParam,credType)
    let data = {
      credType:credType.value == "身份证" ? '111' : '',
      reportParam: reportParamName.value,
      // customName: JIAMIPublicData(customName.value),
      customName: customName.value ? JIAMIPublicData(customName.value) :customName.value,
      // credNum: JIAMIPublicData(credNum.value),
      credNum: credNum.value ? JIAMIPublicData(credNum.value) : credNum.value,
      sex: sex.value,
      reportType: reportType.value,
      birthday: birthday.value,
      remark: remark.value
    }  
    createInspectionTask(data).then((res: any) => {
        show.value = true
        Toast(res.msg)
        // return
        if(res.code == 200) {
          sessionStorage.setItem('taskCode',res.taskCode)
          setTimeout(() => {
            router.push({ path: '/inviteCode', query: { expirationTime: res.expirationTime, longUrl: res.longUrl, shortUrl: res.shortUrl,isShow:1 ,isTask:1} })
          }, 1700);
        }
    })
  }
}
</script>

<!-- less嵌套设置 -->
<style>
.van-field__control:read-only {
 text-align: right;
}
</style>
<style lang="less" scoped>
.crn{
  font-size: 13px;
  color: rgb(255, 0, 0);
}
.pageDdingCustomersPad {
  width: 100%;
  height: 100%;
  border-radius: 10px;
  background: #FFFFFF;
  overflow-y: auto;
  .content {
    width: 100%;
    :deep(.van-cell-group--inset) {
      padding: 0 10px;
    }
    :deep(.van-cell) {
      margin-top: 27px;
      border-radius: 4px;
      background: #F6F9FD;
    }
    .seat {
      width: 100%;
      height: 30px;
    }
    .primaryButton {
      margin-top: 28px;
      width: 100%;
      height: 58px;
      background: url("/src/assets/img/loginIcon/loginBut.png");
      background-size: 100% 100%;
      border: none;
      color: white;
      font-size: 16px;
      margin-bottom: 5px;
    }
  }
}
</style>

<!-- 
  姓名	        输入	  文本框	   是		   只可输入为2-32位字符
  身份证号	     输入	   文本框	    是		
  性别	        仅展示	 文本			        根据输入的身份证号，自动识别出性别进行展示
  出生日期	     仅展示	  文本			       根据输入的身份证号，自动识别出出生日期进行展示，格式为YYYY-MM-DD
  报告类型	     选择	   单选按钮	  是		
  演示期间	     选择	   下拉框	    是		 演示期间有终身、30年、20年、10年，默认勾选终身。
  生成邀请链接		按钮			
-->